const { spawn } = require('child_process')
const { createServer } = require('vite')
const electron = require('electron')

let electronProcess = null
let manualRestart = false

function startRenderer() {
  return new Promise((resolve, reject) => {
    const server = spawn('npm', ['run', 'dev'], {
      cwd: process.cwd(),
      stdio: 'inherit',
      shell: true
    })
    
    server.on('close', code => {
      if (code !== 0) {
        reject(new Error(`Renderer process exited with code ${code}`))
      }
    })
    
    // 等待服务器启动
    setTimeout(() => {
      resolve()
    }, 3000)
  })
}

function startElectron() {
  const args = ['.']
  
  electronProcess = spawn(electron, args, {
    cwd: process.cwd(),
    stdio: 'inherit'
  })
  
  electronProcess.on('close', () => {
    if (!manualRestart) {
      process.exit()
    }
  })
}

function restartElectron() {
  manualRestart = true
  if (electronProcess) {
    electronProcess.kill()
  }
  setTimeout(() => {
    manualRestart = false
    startElectron()
  }, 1000)
}

async function init() {
  try {
    console.log('Starting development server...')
    await startRenderer()
    console.log('Starting Electron...')
    startElectron()
  } catch (error) {
    console.error('Failed to start development environment:', error)
    process.exit(1)
  }
}

init()